﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using FrameDisplay.Services;
using FrameDisplayServer.Services.WebInterface;
using System.ComponentModel;

namespace FrameDisplayServer.Services
{
    
    public class ServiceManager : IServiceManager
    {
        private BackgroundWorker worker;
        private ServiceHost host;
        private ServiceHost hostForWebInterface;


        public ServiceManager()
        {
        }

        public string BaseUrl
        {
            get 
            {
                int port = AppCentral.SettingsManager.Port;
                string baseAddress = "http://" + Environment.MachineName + ":" + port + "/";
                return baseAddress;
            }
        }

        public void StartServices()
        {
            this.worker = new BackgroundWorker();
            this.worker.DoWork += delegate
            {
                this.StartServicesWorker();
            };
            this.worker.RunWorkerAsync();
        }

        private void StartServicesWorker()
        {
            string baseAddress = this.BaseUrl;

            {
                string serviceAddress = baseAddress + "FrameDisplayService";

                this.host = new ServiceHost(typeof(FrameDisplayService), new Uri(serviceAddress));

                WebHttpBinding webHttpBinding = new WebHttpBinding();
                webHttpBinding.MaxReceivedMessageSize = 10000000;

                WebHttpBehavior webHttpBehavior = new WebHttpBehavior();

                ServiceEndpoint endPoint = this.host.AddServiceEndpoint(typeof(IFrameDisplayService), webHttpBinding, "");
                endPoint.Behaviors.Add(webHttpBehavior);

                this.host.Open();
            }

            {
                string serviceAddress = baseAddress + "Web";

                this.hostForWebInterface = new ServiceHost(typeof(WebInterfaceService), new Uri(serviceAddress));

                WebHttpBinding webHttpBinding = new WebHttpBinding();
                webHttpBinding.MaxReceivedMessageSize = 10000000;

                WebHttpBehavior webHttpBehavior = new WebHttpBehavior();

                ServiceEndpoint endPoint = this.hostForWebInterface.AddServiceEndpoint(typeof(IWebInterfaceService), webHttpBinding, "");
                endPoint.Behaviors.Add(webHttpBehavior);

                this.hostForWebInterface.Open();
            }
        }

        public void StopServices()
        {
            if (this.host != null)
            {
                this.host.Close();
            }

            if (this.hostForWebInterface != null)
            {
                this.hostForWebInterface.Close();
            }
        }


    }

}
